import React, { useState } from 'react';
import { NavBar, Input, Button, Avatar } from 'antd-mobile';
import { LeftOutline, SmileOutline, PictureOutline, SoundOutline } from 'antd-mobile-icons';
import styles from './Operation.module.css';
import { useNavigate } from 'react-router-dom';

const Support = () => {
  const navigate = useNavigate();
  const [message, setMessage] = useState('');
  const [chatHistory, setChatHistory] = useState([
    {
      type: 'system',
      content: '您好，欢迎来到客服中心，请问有什么可以帮助您的？',
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    }
  ]);

  const handleBack = () => {
    navigate(-1);
  };

  // 自动回复逻辑
  const getAutoReply = (userMsg) => {
    const trimmedMsg = userMsg.trim().toLowerCase();
  
    const greetings = ['你好', '您好', '在吗', '喂', 'hi', 'hello'];
    if (greetings.some(greet => trimmedMsg.includes(greet))) {
      return '您好，我是智能客服，有什么可以帮您的吗？';
    }
  
    if (['好', '好的', '收到', '嗯', '嗯嗯', 'ok'].includes(trimmedMsg)) {
      return '好的亲~ 有其他问题随时找我哦～';
    }
  
    if (trimmedMsg.includes('查看订单') || trimmedMsg.includes('订单')) {
      return '__show_order_card__';
    }
  
    if (trimmedMsg.includes('发货') || trimmedMsg.includes('什么时候送达')) {
      return '您的订单最晚将在2天内发货，请耐心等待~';
    }
  
    const knownKeywords = ['退款', '发票', '快递', '物流', '支付'];
    if (knownKeywords.some(keyword => trimmedMsg.includes(keyword))) {
      return '正在为您查询相关信息，请稍等片刻。';
    }
  
    return '我暂时无法理解您的问题，稍后将为您转接人工客服，请稍等…';
  };
  

  const handleSend = () => {
    if (!message.trim()) return;

    const userMessage = {
      type: 'user',
      content: message,
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    };

    const updatedHistory = [...chatHistory, userMessage];
    setChatHistory(updatedHistory);
    setMessage('');

    // 模拟延迟自动回复
    setTimeout(() => {
      const reply = getAutoReply(message);

      const systemMessage = {
        type: 'system',
        content: reply,
        time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      };

      setChatHistory([...updatedHistory, systemMessage]);
    }, 1000);
  };

  return (
    <div className={styles.supportContainer}>
      <NavBar 
        backArrow={<LeftOutline />}
        onBack={handleBack}
        className={styles.navBar}
      >
        在线客服
      </NavBar>

      <div className={styles.chatContainer}>
        {chatHistory.map((msg, index) => (
          <div 
            key={index} 
            className={`${styles.messageItem} ${msg.type === 'user' ? styles.userMessage : styles.systemMessage}`}
          >
            {msg.type === 'system' && (
              msg.content === '__show_order_card__' ? (
                <div className={styles.orderCard}>
                  <div className={styles.orderTitle}>订单编号：1234567890</div>
                  <div>商品：运动鞋</div>
                  <div>数量：2</div>
                  <div>总价：￥599.00</div>
                  <div>下单时间：2025-07-3 13:41</div>
                  <div>状态：退款中</div>
                  <div className={styles.messageTime}>{msg.time}</div>
                </div>
              ) : (
                <>
                  <Avatar src="https://picsum.photos/100" className={styles.avatar} />
                  <div className={styles.messageContent}>
                    <div className={styles.messageBubble}>{msg.content}</div>
                    <div className={styles.messageTime}>{msg.time}</div>
                  </div>
                </>
              )
            )}

            {msg.type === 'user' && (
              <>
                <div className={styles.messageContent}>
                  <div className={styles.messageBubble}>{msg.content}</div>
                  <div className={styles.messageTime}>{msg.time}</div>
                </div>
                <Avatar src="https://picsum.photos/101" className={styles.avatar} />
              </>
            )}
          </div>
        ))}
      </div>

      <div className={styles.inputContainer}>
        <div className={styles.inputTools}>
          <SoundOutline className={styles.inputIcon} />
          <Input
            className={styles.messageInput}
            placeholder="请输入您的问题"
            value={message}
            onChange={val => setMessage(val)}
          />
          <SmileOutline className={styles.inputIcon} />
          <PictureOutline className={styles.inputIcon} />
        </div>
        <Button 
          className={styles.sendButton}
          onClick={handleSend}
        >
          发送
        </Button>
      </div>
    </div>
  );
};

export default Support;
